import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import { aoutCoup, saveUserJwt } from '../../contents/jinritemai/componets/coupon/autoHome/autoCoupFunc'
import { getProdectList } from "@Api/productApi"
import { bindinfo, getDlyUserInfo, getBuyCounpStatus } from "@Api/webServerApi"
import db from "@tools/indexDB";
import { store } from "~store"

export interface autoCounpsType {
    autoSetCounterList: object[],
    aoutCoupShopInfo: any,
    addnewPrd: boolean,
    peodecuList: any[],
    getprodectStatus: boolean,
    dlyUserInfo: any,
    dlyUserBuyAutoInfo: object
}
let addLimitStop = 50
export const getProductList = createAsyncThunk('autoCounps/getProductList', async (data: any, { getState, dispatch }) => {
    // console.log('data加载商品', data)
    const shearDater = {
        page: 0,
        pageSize: 20,
        check_status: 3,
        status: 0,
        business_type: 4,
        is_online: 1,
        not_for_sale_search_type: 1
    }

    // console.log('getState()', getState())
    // const { getprodectStatus } = getState().autoCounps as any

    return new Promise((resolve, reject) => {
        dispatch(autoCounps.actions.setLodinGetProducts(true))
        if (data) {
            getProductApi(shearDater, resolve)
            return
        }
        const getInfoProductList: any = localStorage.getItem('infoProdectList')

        try {
            const toJSONs = JSON.parse(getInfoProductList)
            if (!toJSONs) {
                getProductApi(shearDater, resolve)
                return
            }
            // if (!toJSONs.list || !toJSONs.list.length) {
            //     getProductApi(shearDater, resolve)
            //     return
            // }
            // 查看时间的问题
            // console.log('时间', toJSONs.create_time, Date.now() - 1000 * 60 * 60 * 24 * 1)
            if (toJSONs.create_time < (Date.now() - 1000 * 60 * 60 * 24 * 1)) {
                const addProductList = {
                    create_time: Date.now(),
                    page: 0,
                    total: 0
                    // list: getPredectListall
                }
                localStorage.setItem('infoProdectList', JSON.stringify(addProductList))
            }
            if (toJSONs.create_time < (Date.now() - 1000 * 60 * 60 * 24 * 1) || ((toJSONs.page + 1) * 20 < toJSONs.total)) {
                // console.log('时间过期')
                const getTooPage = localStorage.getItem('infoProdectList')
                try {
                    const toJsonStr = JSON.parse(getTooPage)
                    shearDater.page = toJsonStr.page
                } catch (error) {

                }
                getProductApi(shearDater, resolve)
                return
            }
            let { userShopId = '' } = store.getState().jinritemaiShops
            // console.log('userShopId', userShopId)
            db.prodectList.where('shop_id').anyOf(userShopId).toArray((res: any) => {
                // console.log('数据结果', res)
                resolve(res)
            }).catch((err) => {
                console.log('数据错误', err)
            })
            // resolve(toJSONs.list)

        } catch (error) {
            getProductApi(shearDater, resolve)
        }

    })
})

function getProductApi(shearDater, resolve) {
    getProdectList(shearDater).then((res: any) => {
        // if (res.code) {
        //     message.error(res.msg)
        //     setGoodsLoading(false)
        //     return
        // }
        getPredectListall = forMartQuerData(res.data) || []
        if (res.total <= 700) {
            addLimitStop = 70
            // addLimitStop = 70
        }
        // goodsDataInfoCont.total = res.total
        // setGoodsDaraInfoCont({ ...goodsDataInfoCont })

        // shearDater.page = 0
        const addProductList = {
            create_time: Date.now(),
            page: shearDater.page,
            total: res.tools
            // list: getPredectListall
        }
        localStorage.setItem('infoProdectList', JSON.stringify(addProductList))
        getPredectMiter(res.total, shearDater, (data) => {
            let { userShopId = '' } = store.getState().jinritemaiShops
            // console.log('userShopId22', userShopId)
            db.prodectList.where('shop_id').anyOf(userShopId).toArray((res: any) => {
                // console.log('数据结果', res)
                resolve(res)
            }).catch((err) => {
                console.log('数据错误', err)
            })
            // resolve(data)
        })
    })
}

export const getDlyUserBindInfos = createAsyncThunk('autoCounps/getDlyUserBindInfos', async (data: any, { getState, dispatch }) => {
    return new Promise((resolve, reject) => {
        // const getToken = localStorage.getItem('dlyUserToken')
        // if (getToken) {
        //     return
        // }
        bindinfo().then(res => {
            // console.log('binginfos', res)
            if (res?.total) {
                localStorage.setItem('dlyUserToken', res.tokens.token)
                localStorage.setItem('dlyUserRefreshToken', res.tokens.refresh_token)
                saveUserJwt(res.tokens.token)
                // resolve(res)
            } else {
                localStorage.setItem('dlyUserToken', '')
                localStorage.setItem('dlyUserRefreshToken', '')
            }
            resolve(res)
        })
    })
})

export const getDlyUserInfoAction = createAsyncThunk('autoCounps/getDlyUserInfoAction', async (data: any, { getState, dispatch }) => {
    return new Promise((resolve, reject) => {
        const getToken = localStorage.getItem('dlyUserToken')
        if (!getToken) {
            return
        }
        getDlyUserInfo().then(res => {
            // console.log('userinfo', res)
            resolve(res)
        })
    })
})

export const getBuyCounpStatusAction = createAsyncThunk('autoCounps/getBuyCounpStatusAtction', async (data: any, { getState, dispatch }) => {
    return new Promise((resolve, reject) => {

        getBuyCounpStatus().then(res => {
            resolve(res)
        })
    })
})


let addInfoLimit = 0
let getPredectListall: any[] = []
let errpage: any[] = []
let cletaerDtae
function getPredectMiter(total, shearDater, cb) {
    addInfoLimit = 0
    // 是否加载全部
    const getallData: any = []
    let { userShopId = '' } = store.getState().jinritemaiShops
    console.log('userShopId', userShopId)
    while ((shearDater.pageSize * (shearDater.page + 1)) < total && addInfoLimit < addLimitStop) {
        // console.log('chetraer', ((shearDater.pageSize * (shearDater.page + 1)) < total) && (addInfoLimit < addLimitStop))
        addInfoLimit += 1
        // console.log('addNums', addInfoLimit, addLimitStop)
        getallData.push(getProdectList(shearDater))
        shearDater.page++

    }
    // console.log('getallData', getallData)

    Promise.all(getallData).then(resit => {
        // console.log('resit', resit)
        resit.forEach(resdata => {
            if (!resdata.code) {
                // getPredectListall.push(...forMartQuerData(resdata.data))
                const addProductList = {
                    create_time: Date.now(),
                    page: shearDater.page,
                    total
                    // list: getPredectListall
                }
                localStorage.setItem('infoProdectList', JSON.stringify(addProductList))
                db.prodectList.bulkPut(resdata.data.map(res => {
                    res.shop_id = userShopId
                    return res
                }))
            } else {
                errpage.push({
                    config: resdata.config
                })
            }
        })

        if ((shearDater.pageSize * (shearDater.page + 1)) < total) {
            cletaerDtae = setTimeout(_ => {
                // console.log('继续获取', getPredectListall)
                getPredectMiter(total, shearDater, cb)
            }, 5000)
            return
        } else {
            // console.log('获取完成', getPredectListall)
            const addProductList = {
                create_time: Date.now(),
                page: shearDater.page,
                total
                // list: getPredectListall
            }
            localStorage.setItem('infoProdectList', JSON.stringify(addProductList))
            cb && cb(getPredectListall)
        }
    })
}

function forMartQuerData(data) {
    return data.map(resaqer => {
        return {
            img: resaqer.img,
            name: resaqer.name,
            product_id: resaqer.product_id,
            sell_num: resaqer.sell_num,
            stock_num: resaqer.stock_num,
            price: (() => {
                const { price_lower, price_higher } = resaqer
                return price_lower === price_higher ? (price_lower / 100).toFixed(2) : `${(price_lower / 100).toFixed(2)}~${(price_higher / 100).toFixed(2)}`

            })(),
        }
    })
}

// 列表获取 后期异步获取数据 修改缓存
const autoCounps = createSlice({
    name: "jinritemaiAutoCounps",
    initialState: <autoCounpsType>{
        autoSetCounterList: [],
        aoutCoupShopInfo: {},
        addnewPrd: false,
        peodecuList: [],
        getprodectStatus: false,
        dlyUserInfo: {},
        dlyUserBuyAutoInfo: {}
    },
    reducers: {
        setAutoSetCounterListStor: (start, action: { payload: any[] }) => {
            start.autoSetCounterList = action.payload
            // console.log('背景页修改', start.autoSetCounterList)
            // console.log('最终需要保存的数据', start.autoSetCounterList)
            localStorage.setItem(`autoSetCoupon_${start.aoutCoupShopInfo.id}`, JSON.stringify(start.autoSetCounterList))
            // aoutCoup(start.autoSetCounterList)
            // 到这里保存
        },
        setAutoSetCounterListStorAndRun: (start, action: { payload: any[] }) => {
            start.autoSetCounterList = action.payload
            // console.log('背景页修改', start.autoSetCounterList)
            // console.log('最终需要保存的数据', start.autoSetCounterList)
            localStorage.setItem(`autoSetCoupon_${start.aoutCoupShopInfo.id}`, JSON.stringify(start.autoSetCounterList))
            aoutCoup(start.autoSetCounterList)
            // 到这里保存
        },
        getAutoSetCounterListStor: (start, action: { payload: any }) => {
            start.aoutCoupShopInfo = action.payload
            try {
                const listDataStr: any = localStorage.getItem(`autoSetCoupon_${action.payload.id}`)
                const listData = JSON.parse(listDataStr)
                // console.log('listData', listData)
                start.autoSetCounterList = listData || []
            } catch (error) {
                // console.log('解析失败', error)
                start.autoSetCounterList = []
            }
        },
        segtNewProInstall(start, action: { payload: any }) {
            // console.log('色号123456')
            start.addnewPrd = action.payload
        },
        setLodinGetProducts(start, action: { payload: any }) {
            start.getprodectStatus = action.payload
        }
    },
    extraReducers: (builder) => {

        builder.addCase(getProductList.fulfilled, (start, action: { payload: any }) => {
            // console.log('action.payloadaction.payload', action.payload)
            start.peodecuList = action.payload
            start.getprodectStatus = false
            // start.getprodectStatus = true
        })
        builder.addCase(getDlyUserBindInfos.fulfilled, (start, action: { payload: any }) => {
            // console.log('action.payloadaction.payload', action.payload)
            // start.peodecuList = action.payload
            // start.getprodectStatus = false
            // // start.getprodectStatus = true
            // console.log('getDatas', action.payload)
        })
        builder.addCase(getDlyUserInfoAction.fulfilled, (start, action: { payload: any }) => {
            // console.log('action.payloadaction.payload', action.payload)
            // start.peodecuList = action.payload
            // start.getprodectStatus = false
            // // start.getprodectStatus = true
            // console.log('getDatas', action.payload)
            start.dlyUserInfo = action.payload
        }),
            builder.addCase(getBuyCounpStatusAction.fulfilled, (start, action: { payload: any }) => {
                // console.log('action.payloadaction.payload', action.payload)
                // start.peodecuList = action.payload
                // start.getprodectStatus = false
                // // start.getprodectStatus = true
                // console.log('getDatas', action.payload)
                start.dlyUserBuyAutoInfo = action.payload
            })
    },
})

export const { setAutoSetCounterListStor, getAutoSetCounterListStor, setAutoSetCounterListStorAndRun, segtNewProInstall } = autoCounps.actions

export default autoCounps.reducer